package com.hq.utils;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {
	private static SqlSessionFactory sessionFactory;
	
	static {
		try {
			String str = "mybatis-config.xml";
			InputStream inputStream;
			inputStream = Resources.getResourceAsStream(str);
			sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	public MyBatisUtil() {}
	
	public static SqlSessionFactory newInstance() {
		return sessionFactory;
	}

	public static SqlSession getSqlSession(boolean b) {
		//true 关闭事务
		//false 开启事务
		return sessionFactory.openSession(b);
	}
	
	public static void closeSqlSession(SqlSession session) {
		if(session != null) {
			session.close();
			session = null;
		}
	}
	
}
